package it.prova.elementedit;

import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.DropRequest;
import org.eclipse.jst.pagedesigner.commands.CreateItemCommand;
import org.eclipse.jst.pagedesigner.dom.DOMPosition;
import org.eclipse.jst.pagedesigner.dom.DOMPositionHelper;
import org.eclipse.jst.pagedesigner.dom.IDOMPosition;
import org.eclipse.jst.pagedesigner.itemcreation.ItemCreationEditPolicy;
import org.eclipse.jst.pagedesigner.itemcreation.ItemCreationRequest;
import org.eclipse.jst.pagedesigner.parts.ElementEditPart;
import org.eclipse.jst.pagedesigner.viewer.DesignPosition;
import org.w3c.dom.Node;

@SuppressWarnings("restriction")
public class MyElementCreationEditPolicy extends ItemCreationEditPolicy
{	
	public MyElementCreationEditPolicy(ElementEditPart part)
	{
		super();
		setHost(part);
	}
	
	@Override
	public Command getCommand(Request request)
	{
		if (request instanceof ItemCreationRequest)
		{
			ItemCreationRequest r = (ItemCreationRequest) request;
			DesignPosition position = findPosition((DropRequest)request);
			
			if (position == null)
			{
				return null;
			}

			IDOMPosition domposition = DOMPositionHelper.toDOMPosition(position);
			if (domposition == null)
			{
				return null;
			}

			// since the head tag is a widget, the offset will need 
			// to be updated in the position so that new node is
			// appended to the list of children.
			Node node = domposition.getContainerNode();
			domposition = new DOMPosition(node, node.getChildNodes().getLength());

			return new CreateItemCommand
			(
				"ItemCreationEditPolicy.CommandLabel.CreateItem",
				getViewer(getHost()).getModel(), 
				domposition, 
				r.getTagCreationProvider()
			);
		}
		return null;
	}
}